package cn.zhoushengdao.bingwallpaper

import android.app.WallpaperManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.URL
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter

//val LocaleToTimezone = mapOf(
//    "de-DE" to "Europe/Berlin",
//    "en-CA" to "America/Toronto",
//    "en-GB" to "Europe/London",
//    "en-IN" to "Asia/Kolkata",
//    "en-US" to "America/Los_Angeles",
//    "es-ES" to "Europe/Madrid",
//    "fr-CA" to "America/Toronto",
//    "fr-FR" to "Europe/Paris",
//    "it-IT" to "Europe/Rome",
//    "ja-JP" to "Asia/Tokyo",
//    "pt-BR" to "America/Sao_Paulo",
//    "zh-CN" to "Asia/Shanghai"
//)

class WallpaperViewModel @Inject constructor(
    private val data: AppData
) : ViewModel() {
    annotation class Inject

    val wallpapers = mutableStateOf<List<WallpaperData>>(emptyList())
    val isLoading = mutableStateOf(true)
    val error = mutableStateOf<String?>(null)
    val setWallpaperResult = mutableStateOf<Boolean?>(null)

    // 屏幕尺寸参数
    var screenWidth = 1080
    var screenHeight = 1920

    fun setScreenSize(width: Int, height: Int) {
        screenWidth = width
        screenHeight = height
        refreshCurrentWallpaper()
    }

    fun refreshCurrentWallpaper() {
        isLoading.value = true
        error.value = null
        loadWallpapers()
    }

    private fun loadWallpapers() {
        viewModelScope.launch {
            try {
                val bingWallpapers = fetchBingWallpapers()
                if (bingWallpapers.isNotEmpty()) {
                    wallpapers.value = bingWallpapers
                } else {
                    error.value = "未获取到壁纸数据"
                }
            } catch (e: Exception) {
                error.value = e.message ?: "网络请求失败"
                Log.e("WallpaperApp", "加载壁纸失败", e)
            } finally {
                isLoading.value = false
            }
        }
    }

    private suspend fun getImageDate(time: String): String {
        // 解析输入时间为 UTC 时间
        val utcDateTime = LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyyMMddHHmm"))
            .atOffset(ZoneOffset.UTC).toLocalDateTime()

        // 获取目标时区（如果找不到时区则回退到 UTC）
        val targetZone = LocaleToTimezone[data.currentLocale.first()]?.let { ZoneId.of(it) }
            ?: ZoneOffset.UTC

        // 转换为目标时区并格式化日期
        val formattedDate = utcDateTime.atOffset(ZoneOffset.UTC).atZoneSameInstant(targetZone)
            .format(DateTimeFormatter.ISO_LOCAL_DATE)

        return formattedDate
    }

    private suspend fun fetchBingWallpapers(): List<WallpaperData> {
        return withContext(Dispatchers.IO) {
            val images =
                JSONObject(URL("https://services.bingapis.com/ge-apps/api/v2/bwc/hpimages?mkt=${data.currentLocale.first()}").readText()).getJSONArray(
                    "images"
                )
            val result = mutableListOf<WallpaperData>()
            for (i in 0 until images.length()) {
                val image = images.getJSONObject(i)
                val mapLink = image.optJSONObject("mapLink")

                @Suppress("SpellCheckingInspection") result.add(
                    WallpaperData(
                        date = getImageDate(image.getString("fullstartdate")),
                        imageUrl = image.getString("urlbase"),
                        copyright = image.getString("copyrighttext"),
                        searchUrl = image.getString("copyrightlink"),
                        title = image.getString("title"),
                        description = image.getString("description"),
                        headline = image.getString("headline"),
                        quizUrl = image.getString("quiz"),
                        mapImage = mapLink?.optString("Url", "") ?: "",
                        mapUrl = mapLink?.optString("Link", "") ?: "",
                    )
                )
            }
            result
        }
    }

    fun setWallpaper(wallpaper: WallpaperData, context: Context) {
        viewModelScope.launch(Dispatchers.IO) {
            try {
                // 生成完整图片URL（添加尺寸参数）
                val imageUrl = wallpaper.getFullImageUrl(screenWidth, screenHeight)

                // 加载壁纸位图
                val bitmap = loadWallpaperBitmap(imageUrl)
                if (bitmap == null) {
                    setWallpaperResult.value = false
                    Log.e("WallpaperViewModel", "加载壁纸图片失败: $imageUrl")
                    return@launch
                }

                // 设置壁纸
                WallpaperManager.getInstance(context).setBitmap(bitmap)
                data.setCurrentWallpaperUrl(wallpaper.imageUrl)
                setWallpaperResult.value = true
                Log.i("WallpaperViewModel", "壁纸设置成功: $imageUrl")
            } catch (e: Exception) {
                setWallpaperResult.value = false
                Log.e("WallpaperViewModel", "设置壁纸失败", e)
            }
        }
    }

    fun clearSetWallpaperResult() {
        setWallpaperResult.value = null
    }

    suspend fun loadWallpaperBitmap(url: String): Bitmap? {
        return withContext(Dispatchers.IO) {
            try {
                val connection = URL(url).openConnection()
                connection.connect()
                val input = connection.getInputStream()
                BitmapFactory.decodeStream(input)
            } catch (e: Exception) {
                Log.e("WallpaperViewModel", "加载壁纸图片失败: $url", e)
                null
            }
        }
    }
}

class WallpaperViewModelFactory(
    private val data: AppData
) : ViewModelProvider.Factory {
    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(WallpaperViewModel::class.java)) {
            return WallpaperViewModel(data) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
